/**
* Author: fulishang
* Create Time  : 2016年8月20日,下午11:41:23
* Modify Time :
* Desc  : 
*/
package com.sam.si.dc.handler;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.sam.si.dc.metadata.Field;
import com.sam.si.dc.metadata.Fields;
import com.sam.si.dc.metadata.FileCatalog;

@Component
public class XmlHandler {
	
	private Logger LOGGER = Logger.getLogger(XmlHandler.class);

	@Value("${filecatalog.path}")
	private String fileCatalogPath;
	
	@Value("${fields.path}")
	private String fieldsPath;
	
	public Map<String, List<Field>> fieldsMap = new HashMap<>();
	public Map<String, FileCatalog> fileCatalogMap = new HashMap<>();
	
	public Map<String, List<Field>> unMarshallFields() throws Exception{
	    JAXBContext jaxbContext = JAXBContext.newInstance(Fields.class);
	    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
	    
	    LOGGER.info("Initialize the the fields from path -- " + fieldsPath);
	    
	    File file = new File(fieldsPath);
	    
	    File[] fileList = file.listFiles();
	    
	    if (fileList.length==0){
	    	LOGGER.info("no field files found!!!");
	    	throw new Exception("No field files found!");
	    }
	   
	    for(int i=0; i<fileList.length; i++) {
	    	Fields fields = (Fields) jaxbUnmarshaller.unmarshal(new File(fileList[i].getPath()));
		    List<Field> fieldList = new ArrayList<>();
	    	for (Field field : fields.getFields()) {
	    		fieldList.add(field);
	    	}
	    	fieldsMap.put(fields.getId(), fieldList);
	    }
	    
	    LOGGER.info("Initialize fields done!");
	    
	    for (Map.Entry<String, List<Field>> map : fieldsMap.entrySet()) {
	    	LOGGER.info(map.getKey());
	    	List<Field> list = map.getValue();
	    	for (Field f : list) {
	    		LOGGER.info(f.getFieldName());
	    	}
	    }
	    
	    return fieldsMap;
	}
	
	public Map<String, FileCatalog> unMarshallFileCatalog() throws Exception{
	    JAXBContext jaxbContext = JAXBContext.newInstance(FileCatalog.class);
	    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
	    

	    LOGGER.info("Initialize the the file catalog from path --" + fileCatalogPath);
	    
	    File file = new File(fileCatalogPath);
	    
	    File[] fileList = file.listFiles();
	    
	    if (fileList.length==0){
	    	LOGGER.info("no field files found!!!");
	    	throw new Exception("No field files found!");
	    }
	    
	    for (int i=0; i<fileList.length; i++) {
	    	FileCatalog fileCatalog = (FileCatalog) jaxbUnmarshaller.unmarshal( new File(fileList[i].getPath()) );
	    	fileCatalogMap.put(fileCatalog.getId(), fileCatalog);
	    }
	    
	    LOGGER.info("Initialize filecatalog done!");
	    return fileCatalogMap;
	}
		
	
}
